import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 电视遥控器按键处理服务
class RemoteControlService {
  static final RemoteControlService _instance = RemoteControlService._internal();
  
  factory RemoteControlService() => _instance;
  
  RemoteControlService._internal();
  
  /// 当前焦点节点
  FocusNode? _currentFocusNode;
  
  /// 焦点节点列表
  final List<FocusNode> _focusNodes = [];
  
  /// 当前焦点索引
  int _currentFocusIndex = 0;
  
  /// 注册焦点节点
  void registerFocusNode(FocusNode node) {
    if (!_focusNodes.contains(node)) {
      _focusNodes.add(node);
    }
  }
  
  /// 注销焦点节点
  void unregisterFocusNode(FocusNode node) {
    _focusNodes.remove(node);
  }
  
  /// 处理遥控器按键事件
  bool handleKeyEvent(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      final logicalKey = event.logicalKey;
      
      // 方向键导航
      if (logicalKey == LogicalKeyboardKey.arrowDown) {
        _moveFocus(1); // 向下移动焦点
        return true;
      } else if (logicalKey == LogicalKeyboardKey.arrowUp) {
        _moveFocus(-1); // 向上移动焦点
        return true;
      } else if (logicalKey == LogicalKeyboardKey.arrowRight) {
        _moveFocus(1); // 向右移动焦点
        return true;
      } else if (logicalKey == LogicalKeyboardKey.arrowLeft) {
        _moveFocus(-1); // 向左移动焦点
        return true;
      }
      
      // 确认键（Enter、Select、OK）
      else if (logicalKey == LogicalKeyboardKey.enter ||
               logicalKey == LogicalKeyboardKey.select ||
               logicalKey == LogicalKeyboardKey.gameButtonA) {
        _triggerCurrentFocus();
        return true;
      }
      
      // 返回键（Escape、Back）
      else if (logicalKey == LogicalKeyboardKey.escape ||
               logicalKey == LogicalKeyboardKey.goBack) {
        // 处理返回逻辑
        return _handleBackButton();
      }
      
      // 数字键快捷导航
      else if (logicalKey == LogicalKeyboardKey.digit1) {
        _jumpToFocus(0);
        return true;
      } else if (logicalKey == LogicalKeyboardKey.digit2) {
        _jumpToFocus(1);
        return true;
      } else if (logicalKey == LogicalKeyboardKey.digit3) {
        _jumpToFocus(2);
        return true;
      } else if (logicalKey == LogicalKeyboardKey.digit4) {
        _jumpToFocus(3);
        return true;
      }
    }
    
    return false;
  }
  
  /// 移动焦点
  void _moveFocus(int direction) {
    if (_focusNodes.isEmpty) return;
    
    // 移除当前焦点
    if (_currentFocusNode != null) {
      _currentFocusNode!.unfocus();
    }
    
    // 计算新的焦点索引
    _currentFocusIndex = (_currentFocusIndex + direction) % _focusNodes.length;
    if (_currentFocusIndex < 0) {
      _currentFocusIndex = _focusNodes.length - 1;
    }
    
    // 设置新焦点
    _currentFocusNode = _focusNodes[_currentFocusIndex];
    _currentFocusNode!.requestFocus();
  }
  
  /// 跳转到指定焦点
  void _jumpToFocus(int index) {
    if (_focusNodes.isEmpty || index < 0 || index >= _focusNodes.length) return;
    
    if (_currentFocusNode != null) {
      _currentFocusNode!.unfocus();
    }
    
    _currentFocusIndex = index;
    _currentFocusNode = _focusNodes[index];
    _currentFocusNode!.requestFocus();
  }
  
  /// 触发当前焦点元素的点击事件
  void _triggerCurrentFocus() {
    if (_currentFocusNode != null) {
      // 获取当前焦点节点的上下文
      final context = _currentFocusNode!.context;
      if (context != null) {
        // 查找最近的 GestureDetector 或 InkWell 并触发其 onTap 回调
        _findAndTriggerTap(context);
      }
      debugPrint('触发焦点元素操作: $_currentFocusIndex');
    }
  }
  
  /// 递归查找并触发点击事件
  void _findAndTriggerTap(BuildContext context) {
    final element = context as Element;
    
    // 检查当前元素是否为 GestureDetector 或 InkWell
    if (element.widget is GestureDetector) {
      final gestureDetector = element.widget as GestureDetector;
      if (gestureDetector.onTap != null) {
        gestureDetector.onTap!();
        return;
      }
    } else if (element.widget is InkWell) {
      final inkWell = element.widget as InkWell;
      if (inkWell.onTap != null) {
        inkWell.onTap!();
        return;
      }
    }
    
    // 尝试使用 Element 的 visitAncestorElements 方法来查找父元素
    element.visitAncestorElements((ancestor) {
      if (ancestor.widget is GestureDetector) {
        final gestureDetector = ancestor.widget as GestureDetector;
        if (gestureDetector.onTap != null) {
          gestureDetector.onTap!();
          return false; // 停止遍历
        }
      } else if (ancestor.widget is InkWell) {
        final inkWell = ancestor.widget as InkWell;
        if (inkWell.onTap != null) {
          inkWell.onTap!();
          return false; // 停止遍历
        }
      }
      return true; // 继续遍历
    });
  }
  
  /// 处理返回按钮
  bool _handleBackButton() {
    // 尝试从当前焦点节点获取上下文
    BuildContext? context = _currentFocusNode?.context;
    
    // 如果没有焦点上下文，尝试使用全局导航键
    if (context == null && navigatorKey.currentContext != null) {
      context = navigatorKey.currentContext;
    }
    
    if (context != null) {
      final navigator = Navigator.of(context);
      
      // 检查是否可以弹出（是否有页面可以返回）
      if (navigator.canPop()) {
        navigator.pop();
        debugPrint('处理返回按钮 - 返回上一页');
        return true;
      } else {
        // 如果没有页面可以返回，可以处理其他返回逻辑
        debugPrint('处理返回按钮 - 无页面可返回');
        
        // 这里可以添加应用特定的返回逻辑
        // 例如：显示退出确认对话框、最小化应用等
        return false;
      }
    } else {
      // 无法获取导航上下文
      debugPrint('处理返回按钮 - 无法获取导航上下文');
      return false;
    }
  }
  
  // 全局导航键，用于在没有焦点上下文时获取导航状态
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  
  /// 清空所有焦点节点
  void clearAllFocusNodes() {
    for (var node in _focusNodes) {
      node.dispose();
    }
    _focusNodes.clear();
    _currentFocusNode = null;
    _currentFocusIndex = 0;
  }
  
  /// 获取当前焦点索引
  int get currentFocusIndex => _currentFocusIndex;
  
  /// 获取焦点节点数量
  int get focusCount => _focusNodes.length;
}